package com.liu.SRMan.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.g4studio.core.metatype.Dto;
import org.g4studio.core.metatype.impl.BaseDto;
import org.g4studio.core.model.service.impl.BizServiceImpl;
import org.g4studio.core.mvc.xstruts.upload.FormFile;
import org.g4studio.core.orm.xibatis.sqlmap.client.SqlMapClient;
import org.g4studio.core.orm.xibatis.support.SqlMapClientTemplate;
import org.g4studio.core.util.G4Utils;
import org.g4studio.core.web.CommonActionForm;
import org.g4studio.system.common.util.idgenerator.IDHelper;

import com.liu.SRMan.service.LongitudinalService;

public class LongitudinalServiceImpl extends BizServiceImpl implements LongitudinalService  {


	public Dto saveApplyPlan(Dto pDto) {
		Dto outDto = new BaseDto();
		String emid = IDHelper.getUUID();
		
        pDto.put("id", emid);
		g4Dao.insert("Temp.newApplyPlan", pDto);
		
		outDto.put("id", emid);
		return outDto;
	}
	
	public Dto newLongitudinal(Dto inDto,FormFile inFile,String user_id,String savePath) throws SQLException {
		Dto outDto = new BaseDto();
		SqlMapClientTemplate sqlMapTemp = g4Dao.getSqlMapClientTpl();
		SqlMapClient sqlMap = sqlMapTemp.getSqlMapClient();
		
		try{
			sqlMap.startTransaction();
			
			if(inFile.equals(null) || inFile.getFileName().equals("")){
				System.out.println("接收到的表单中的文件：\n" + inFile);
			}else{
				Dto upDto = doUpload(inFile, user_id,savePath);
				String file = upDto.getAsString("fileName");
				inDto.put("attachment", file);
			}
			
			outDto = this.saveLongitudinalProject(inDto);
			String projectID = outDto.getAsString("id");

			JSONArray array = JSONArray.fromObject(inDto.getAsString("strJson"));

			for (int i = 0; i < array.size(); i++) {
				JSONObject jasonObject = (JSONObject) array.get(i);
				Dto memberDto = createMemberDto(jasonObject, projectID);
				this.saveMember(memberDto);
			}

			sqlMap.commitTransaction();
			outDto.put("success", new Boolean(true));
			outDto.put("msg", "横向项目数据保存成功!");
		}catch(Exception e){
			sqlMap.getCurrentConnection().rollback();
			outDto.put("failure", new Boolean(true));
			outDto.put("msg", "横向项目数据保存失败!");
		}finally{
			sqlMap.endTransaction();
		}
		return outDto;
	}
	
	public Dto updateLongitudinal(Dto inDto,FormFile inFile,String user_id,String savePath) throws SQLException {
		Dto outDto = new BaseDto();
		SqlMapClientTemplate sqlMapTemp = g4Dao.getSqlMapClientTpl();
		SqlMapClient sqlMap = sqlMapTemp.getSqlMapClient();
		
		try{
			sqlMap.startTransaction();
			
			if(inFile.equals(null) || inFile.getFileName().equals("")){
				System.out.println("接收到的表单中的文件：\n" + inFile);
			}else{
				deleteFile(inDto.getAsString("attachment"),savePath);
				Dto upDto = doUpload(inFile, user_id,savePath);
				String file = upDto.getAsString("fileName");
				inDto.put("attachment", file);
			}
			
			this.updateLongitudinalProject(inDto);
			this.deleteMembers(inDto);

			JSONArray array = JSONArray.fromObject(inDto.getAsString("strJson"));

			for (int i = 0; i < array.size(); i++) {
				JSONObject jasonObject = (JSONObject) array.get(i);
				Dto memberDto = createMemberDto(jasonObject, inDto.getAsString("id"));
				this.saveMember(memberDto);
			}

			sqlMap.commitTransaction();
			outDto.put("success", new Boolean(true));
			outDto.put("msg", "横向项目数据保存成功!");
		}catch(Exception e){
			sqlMap.getCurrentConnection().rollback();
			outDto.put("failure", new Boolean(true));
			outDto.put("msg", "横向项目数据保存失败!");
		}finally{
			sqlMap.endTransaction();
		}
		return outDto;
	}
	
	public Dto newInspectPlan(Dto inDto,FormFile inFile,String user_id,String savePath)throws SQLException{
		Dto outDto = new BaseDto();
		SqlMapClientTemplate sqlMapTemp = g4Dao.getSqlMapClientTpl();
		SqlMapClient sqlMap = sqlMapTemp.getSqlMapClient();
		
		try{
			sqlMap.startTransaction();
			
			if(inFile.equals(null) || inFile.getFileName().equals("")){
				System.out.println("接收到的表单中的文件：\n" + inFile);
			}else{
				Dto upDto = doUpload(inFile, user_id,savePath);
				String file = upDto.getAsString("fileName");
				inDto.put("attachment", file);
			}
			
			outDto = this.saveInspectPlan(inDto);
			String inspectPlan_id = outDto.getAsString("id");

			JSONArray array = JSONArray.fromObject(inDto.getAsString("strJson"));

			for (int i = 0; i < array.size(); i++) {
				JSONObject jasonObject = (JSONObject) array.get(i);
				Dto inspectPlan = new BaseDto();
				inspectPlan.put("inspect_plan_id", inspectPlan_id);
				inspectPlan.put("project_id", jasonObject.get("id"));
				this.saveInspectPlanProject(inspectPlan);
			}

			sqlMap.commitTransaction();
			outDto.put("success", new Boolean(true));
			outDto.put("msg", "横向项目数据保存成功!");
		}catch(Exception e){
			sqlMap.getCurrentConnection().rollback();
			outDto.put("failure", new Boolean(true));
			outDto.put("msg", "横向项目数据保存失败!");
		}finally{
			sqlMap.endTransaction();
		}
		return outDto;
	}
	
	public Dto deleteLongitudinal(Dto inDto,String fileName,String savePath)throws SQLException{
		Dto outDto = new BaseDto();
		SqlMapClientTemplate sqlMapTemp = g4Dao.getSqlMapClientTpl();
		SqlMapClient sqlMap = sqlMapTemp.getSqlMapClient();
		
		try{
			sqlMap.startTransaction();
			
			if(fileName.equals("")){
				System.out.println("接收到的表单中的文件：\n" + fileName);
			}else{
				deleteFile(fileName,savePath);
			}
			
			this.deleteLongitudinalItem(inDto);
			this.deleteMembers(inDto);

			sqlMap.commitTransaction();
			outDto.put("success", new Boolean(true));
			outDto.put("msg", "横向项目数据删除成功!");
		}catch(Exception e){
			sqlMap.getCurrentConnection().rollback();
			outDto.put("failure", new Boolean(true));
			outDto.put("msg", "横向项目数据删除失败!");
		}finally{
			sqlMap.endTransaction();
		}
		return outDto;
	}
	
	public Dto finishLongitudinal(Dto pDto){
		String userid = pDto.getAsString("loginuserid");
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datetime = tempDate.format(new java.util.Date());
		
		pDto.put("updated_by", userid);
        pDto.put("updated_time", datetime);
        pDto.put("accreditat_time", datetime);
        g4Dao.update("Temp.finishLongitudinal", pDto);
		return null;
	}
	
	
	public Dto deleteLongitudinalItem(Dto pDto){
		Dto outDto = new BaseDto();
		g4Dao.delete("Temp.deleteLongitudinal", pDto);
		return outDto;
	}
	
	public Dto saveLongitudinalProject(Dto pDto) {
		Dto outDto = new BaseDto();
		String emid = IDHelper.getUUID();
		String user_id = pDto.getAsString("loginuserid");
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datetime = tempDate.format(new java.util.Date());
		
		pDto.put("id", emid);
		pDto.put("created_by", user_id);
	    pDto.put("updated_by", user_id);
	    pDto.put("updated_time", datetime);
	    pDto.put("project_phase", "1");
        
		g4Dao.insert("Temp.newLongitudinalProject", pDto);
		
		outDto.put("id", emid);
		return outDto;
	}
	
	public Dto updateLongitudinalProject(Dto pDto) {
		// TODO Auto-generated method stub
		String userid = pDto.getAsString("loginuserid");
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datetime = tempDate.format(new java.util.Date());
		
		pDto.put("updated_by", userid);
        pDto.put("updated_time", datetime);
        g4Dao.update("Temp.updateLongitudinalProject", pDto);
        
		return null;
	}
	
	public Dto deleteMembers(Dto pDto) {
		Dto outDto = new BaseDto();
		g4Dao.delete("Temp.deleteProjectMember", pDto);
		return outDto;
	}
	
	public Dto saveMember(Dto pDto){
		String emid = IDHelper.getUUID();
        pDto.put("id", emid);
        
		g4Dao.insert("Temp.newMember", pDto);
		return null;
	}
	
	
	public Dto saveInspectPlan(Dto pDto){
		Dto outDto = new BaseDto();
		String id = IDHelper.getUUID();
		
		pDto.put("id", id);
		pDto.put("end_date", pDto.get("end_date") + " 23:59:59");
		g4Dao.insert("Temp.newInspectPlan", pDto);
		
		outDto.put("id", id);
		return outDto;
	}
	
	public Dto saveInspectPlanProject(Dto pDto){
		String id = IDHelper.getUUID();
        pDto.put("id", id);
        
		g4Dao.insert("Temp.newInspectPlanProject", pDto);
		return null;
	}
	
	public Dto auditLongitudinal(Dto pDto){
		String userid = pDto.getAsString("loginuserid");
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datetime = tempDate.format(new java.util.Date());
		
		pDto.put("updated_by", userid);
        pDto.put("updated_time", datetime);
        pDto.put("school_check_time", datetime);
        g4Dao.update("Temp.passSchoolAudit", pDto);
		return null;
	}
	private Dto createMemberDto(JSONObject jasonObject, String project_id) {
		Dto memberDto = new BaseDto();
		memberDto.put("project_id", project_id);
		memberDto.put("name", jasonObject.get("mumbername"));
		memberDto.put("empolyee_num", jasonObject.get("empolyee_num"));
		memberDto.put("research", jasonObject.get("research"));
		memberDto.put("sex", jasonObject.get("sex"));
		memberDto.put("professional_title",jasonObject.get("professional_title"));
		memberDto.put("educational", jasonObject.get("educational"));
		memberDto.put("department", jasonObject.get("department"));
		memberDto.put("percent", jasonObject.get("percent"));
		return memberDto;
	}
	
	private Dto doUpload(FormFile myFile, String userid,String savePath) {
		Dto outDto = new BaseDto();
		
		// 检查路径是否存在,如果不存在则创建之
		File file = new File(savePath);
		if (!file.exists()) {
			file.mkdir();
		}
		String type = myFile.getFileName().substring(
				myFile.getFileName().lastIndexOf("."));
		// 文件真实文件名
		String fileName = userid;
		fileName = fileName + "_" + G4Utils.getCurrentTime("yyyyMMddhhmmss")
				+ type;

		File fileToCreate = new File(savePath, fileName);
		if (myFile.getFileSize() > 20480000) {
			outDto.put("success", new Boolean(true));
			outDto.put("msg", "文件上传失败,你只能上传小于10MB的图片文件");
			outDto.put("state", "error");
		} else {
			// 检查同名文件是否存在,不存在则将文件流写入文件磁盘系统
			if (!fileToCreate.exists()) {
				FileOutputStream os;
				try {
					os = new FileOutputStream(fileToCreate);
					os.write(myFile.getFileData());
					os.flush();
					os.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			outDto.put("success", new Boolean(true));
			outDto.put("msg", "文件上传成功");
			outDto.put("fileName", fileName);
		}

		return outDto;
	}

	private void deleteFile(String fileName,String savePath) {
		String files = savePath + fileName;
		File file = new File(files);
		if (file.isFile() && file.exists()) {
			boolean d = file.delete();
		}
	}
}